package com.faner.fast.upms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.faner.fast.base.PageDTO;
import com.faner.fast.constant.CacheConstants;
import com.faner.fast.constant.enums.DictTypeEnum;
import com.faner.fast.upms.mapper.SysDictItemMapper;
import com.faner.fast.upms.model.SysDictDO;
import com.faner.fast.upms.model.SysDictItemDO;
import com.faner.fast.upms.service.SysDictItemService;
import com.faner.fast.upms.service.SysDictService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * 字典项
 *
 * @author lengleng
 * @date 2019/03/19
 */
@Service
@RequiredArgsConstructor
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItemDO> implements SysDictItemService {

    private final SysDictService dictService;

    @Override
    public Page<SysDictItemDO> getSysDictItemPage(PageDTO page, SysDictItemDO item) {
        return this.baseMapper.selectPage(new Page<>(page.getPageNum(), page.getPageSize()), Wrappers.lambdaQuery(item));
    }

    /**
     * 删除字典项
     * @param id 字典项ID
     * @return
     */
    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public Boolean removeDictItem(Long id) {
        // 根据ID查询字典ID
        SysDictItemDO dictItem = this.getById(id);
        SysDictDO dict = dictService.getById(dictItem.getDictId());
        // 系统内置
        Assert.state(!DictTypeEnum.SYSTEM.getType().equals(dict.getSystem()), "系统内置字典项目不能删除");
        return this.removeById(id);
    }

    /**
     * 更新字典项
     * @param item 字典项
     * @return
     */
    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public Boolean updateDictItem(SysDictItemDO item) {
        // 查询字典
        SysDictDO dict = dictService.getById(item.getDictId());
        // 系统内置
        Assert.state(!DictTypeEnum.SYSTEM.getType().equals(dict.getSystem()), "系统内置字典项目不能修改");
        return this.updateById(item);
    }

}
